<?php

namespace App\Providers;

use GuzzleHttp\Client;
use Illuminate\Support\Facades\Event;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Exception;
use Log;

class EventServiceProvider extends ServiceProvider
{
    /**
     * The event listener mappings for the application.
     *
     * @var array
     */
    protected $listen = [
        'App\Events\Event' => [
            'App\Listeners\EventListener',
        ],
    ];

    /**
     * Register any events for your application.
     *
     * @return void
     */
    public function boot()
    {
        parent::boot();

        Log::listen(function ($log) {
            $env     = env('APP_ENV');
            $time    = date('Y-m-d H:i:s');
            $url     = app('request')->fullUrl();
            $params  = app('request')->all();
            $level   = $log->level;
            $message = $log->message;
            $context = $log->context;
            if (isset($context['exception'])) {
                $trace = $context['exception']->getTraceAsString();
            } else {
                $trace = json_encode($context);
            }
            $content = <<<'TPL'
错误信息
时间:{DATE_TIME}
环境:{ENV}
级别:{LEVEL}
接口:{URL}
参数:{PARAMS}
信息:{MESSAGE}
详细:
{TRACE}
TPL;
            if (env('DING_LOG')) {
                try {
                    $client = new Client();
                    $client->request('post', env('DING_LOG'), [
                        'headers' => [
                            'Content-Type' => 'application/json;charset=utf-8',
                        ],
                        'body'    => json_encode([
                            'msgtype' => 'text',
                            'text'    => [
                                'content' => str_replace([
                                    '{URL}',
                                    '{PARAMS}',
                                    '{DATE_TIME}',
                                    '{ENV}',
                                    '{LEVEL}',
                                    '{MESSAGE}',
                                    '{TRACE}',
                                ], [
                                    $url,
                                    var_export($params, true),
                                    $time,
                                    $env,
                                    $level,
                                    $message,
                                    $trace,
                                ], $content),
                            ],
                        ]),
                    ]);
                } catch (Exception $exception) {
                    report($exception);
                }
            }
        });
    }
}
